home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / ssl.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  14KB  |  395 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''This module provides some more Pythonic support for SSL.
  5.  
  6. Object types:
  7.  
  8.   SSLSocket -- subtype of socket.socket which does SSL over the socket
  9.  
  10. Exceptions:
  11.  
  12.   SSLError -- exception raised for I/O errors
  13.  
  14. Functions:
  15.  
  16.   cert_time_to_seconds -- convert time string used for certificate
  17.                           notBefore and notAfter functions to integer
  18.                           seconds past the Epoch (the time values
  19.                           returned from time.time())
  20.  
  21.   fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
  22.                           by the server running on HOST at port PORT.  No
  23.                           validation of the certificate is performed.
  24.  
  25. Integer constants:
  26.  
  27. SSL_ERROR_ZERO_RETURN
  28. SSL_ERROR_WANT_READ
  29. SSL_ERROR_WANT_WRITE
  30. SSL_ERROR_WANT_X509_LOOKUP
  31. SSL_ERROR_SYSCALL
  32. SSL_ERROR_SSL
  33. SSL_ERROR_WANT_CONNECT
  34.  
  35. SSL_ERROR_EOF
  36. SSL_ERROR_INVALID_ERROR_CODE
  37.  
  38. The following group define certificate requirements that one side is
  39. allowing/requiring from the other side:
  40.  
  41. CERT_NONE - no certificates from the other side are required (or will
  42.             be looked at if provided)
  43. CERT_OPTIONAL - certificates are not required, but if provided will be
  44.                 validated, and if validation fails, the connection will
  45.                 also fail
  46. CERT_REQUIRED - certificates are required, and will be validated, and
  47.                 if validation fails, the connection will also fail
  48.  
  49. The following constants identify various SSL protocol variants:
  50.  
  51. PROTOCOL_SSLv2
  52. PROTOCOL_SSLv3
  53. PROTOCOL_SSLv23
  54. PROTOCOL_TLSv1
  55. '''
  56. import textwrap
  57. import _ssl
  58. from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
  59. from _ssl import SSLError
  60. from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
  61. from _ssl import RAND_status, RAND_egd, RAND_add
  62. from _ssl import SSL_ERROR_ZERO_RETURN, SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_SYSCALL, SSL_ERROR_SSL, SSL_ERROR_WANT_CONNECT, SSL_ERROR_EOF, SSL_ERROR_INVALID_ERROR_CODE
  63. from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
  64. _PROTOCOL_NAMES = {
  65.     PROTOCOL_TLSv1: 'TLSv1',
  66.     PROTOCOL_SSLv23: 'SSLv23',
  67.     PROTOCOL_SSLv3: 'SSLv3' }
  68.  
  69. try:
  70.     from _ssl import PROTOCOL_SSLv2
  71.     _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
  72. except ImportError:
  73.     _SSLv2_IF_EXISTS = None
  74.  
  75. _PROTOCOL_NAMES[PROTOCOL_SSLv2] = 'SSLv2'
  76. from socket import socket, _fileobject, _delegate_methods, error as socket_error
  77. from socket import getnameinfo as _getnameinfo
  78. import base64
  79. import errno
  80. _DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
  81.  
  82. class SSLSocket(socket):
  83.     '''This class implements a subtype of socket.socket that wraps
  84.     the underlying OS socket in an SSL context when necessary, and
  85.     provides read and write methods over that channel.'''
  86.     
  87.     def __init__(self, sock, keyfile = None, certfile = None, server_side = False, cert_reqs = CERT_NONE, ssl_version = PROTOCOL_SSLv23, ca_certs = None, do_handshake_on_connect = True, suppress_ragged_eofs = True, ciphers = None):
  88.         socket.__init__(self, _sock = sock._sock)
  89.         for attr in _delegate_methods:
  90.             
  91.             try:
  92.                 delattr(self, attr)
  93.             continue
  94.             except AttributeError:
  95.                 continue
  96.             
  97.  
  98.         
  99.         if ciphers is None and ssl_version != _SSLv2_IF_EXISTS:
  100.             ciphers = _DEFAULT_CIPHERS
  101.         if certfile and not keyfile:
  102.             keyfile = certfile
  103.         
  104.         try:
  105.             socket.getpeername(self)
  106.         except socket_error:
  107.             e = None
  108.             if e.errno != errno.ENOTCONN:
  109.                 raise 
  110.             self._connected = False
  111.             self._sslobj = None
  112.  
  113.         self._connected = True
  114.         self._sslobj = _ssl.sslwrap(self._sock, server_side, keyfile, certfile, cert_reqs, ssl_version, ca_certs, ciphers)
  115.         if do_handshake_on_connect:
  116.             self.do_handshake()
  117.         self.keyfile = keyfile
  118.         self.certfile = certfile
  119.         self.cert_reqs = cert_reqs
  120.         self.ssl_version = ssl_version
  121.         self.ca_certs = ca_certs
  122.         self.ciphers = ciphers
  123.         self.do_handshake_on_connect = do_handshake_on_connect
  124.         self.suppress_ragged_eofs = suppress_ragged_eofs
  125.         self._makefile_refs = 0
  126.  
  127.     
  128.     def read(self, len = 1024):
  129.         '''Read up to LEN bytes and return them.
  130.         Return zero-length string on EOF.'''
  131.         
  132.         try:
  133.             return self._sslobj.read(len)
  134.         except SSLError:
  135.             x = None
  136.             if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
  137.                 return ''
  138.  
  139.  
  140.     
  141.     def write(self, data):
  142.         '''Write DATA to the underlying SSL channel.  Returns
  143.         number of bytes of DATA actually transmitted.'''
  144.         return self._sslobj.write(data)
  145.  
  146.     
  147.     def getpeercert(self, binary_form = False):
  148.         '''Returns a formatted version of the data in the
  149.         certificate provided by the other end of the SSL channel.
  150.         Return None if no certificate was provided, {} if a
  151.         certificate was provided, but not validated.'''
  152.         return self._sslobj.peer_certificate(binary_form)
  153.  
  154.     
  155.     def cipher(self):
  156.         if not self._sslobj:
  157.             return None
  158.         return None._sslobj.cipher()
  159.  
  160.     
  161.     def send(self, data, flags = 0):
  162.         if self._sslobj:
  163.             if flags != 0:
  164.                 raise ValueError('non-zero flags not allowed in calls to send() on %s' % self.__class__)
  165.             while True:
  166.                 
  167.                 try:
  168.                     v = self._sslobj.write(data)
  169.                 except SSLError:
  170.                     x = None
  171.                     if x.args[0] == SSL_ERROR_WANT_READ:
  172.                         return 0
  173.                     if None.args[0] == SSL_ERROR_WANT_WRITE:
  174.                         return 0
  175.                     continue
  176.  
  177.                 return v
  178.         else:
  179.             return self._sock.send(data, flags)
  180.  
  181.     
  182.     def sendto(self, data, flags_or_addr, addr = None):
  183.         if self._sslobj:
  184.             raise ValueError('sendto not allowed on instances of %s' % self.__class__)
  185.         if addr is None:
  186.             return self._sock.sendto(data, flags_or_addr)
  187.         return None._sock.sendto(data, flags_or_addr, addr)
  188.  
  189.     
  190.     def sendall(self, data, flags = 0):
  191.         if self._sslobj:
  192.             if flags != 0:
  193.                 raise ValueError('non-zero flags not allowed in calls to sendall() on %s' % self.__class__)
  194.             amount = len(data)
  195.             count = 0
  196.             while count < amount:
  197.                 v = self.send(data[count:])
  198.                 count += v
  199.             return amount
  200.         return None.sendall(self, data, flags)
  201.  
  202.     
  203.     def recv(self, buflen = 1024, flags = 0):
  204.         if self._sslobj:
  205.             if flags != 0:
  206.                 raise ValueError('non-zero flags not allowed in calls to recv() on %s' % self.__class__)
  207.             return self.read(buflen)
  208.         return None._sock.recv(buflen, flags)
  209.  
  210.     
  211.     def recv_into(self, buffer, nbytes = None, flags = 0):
  212.         if buffer and nbytes is None:
  213.             nbytes = len(buffer)
  214.         elif nbytes is None:
  215.             nbytes = 1024
  216.         if self._sslobj:
  217.             if flags != 0:
  218.                 raise ValueError('non-zero flags not allowed in calls to recv_into() on %s' % self.__class__)
  219.             tmp_buffer = self.read(nbytes)
  220.             v = len(tmp_buffer)
  221.             buffer[:v] = tmp_buffer
  222.             return v
  223.         return None._sock.recv_into(buffer, nbytes, flags)
  224.  
  225.     
  226.     def recvfrom(self, buflen = 1024, flags = 0):
  227.         if self._sslobj:
  228.             raise ValueError('recvfrom not allowed on instances of %s' % self.__class__)
  229.         return self._sock.recvfrom(buflen, flags)
  230.  
  231.     
  232.     def recvfrom_into(self, buffer, nbytes = None, flags = 0):
  233.         if self._sslobj:
  234.             raise ValueError('recvfrom_into not allowed on instances of %s' % self.__class__)
  235.         return self._sock.recvfrom_into(buffer, nbytes, flags)
  236.  
  237.     
  238.     def pending(self):
  239.         if self._sslobj:
  240.             return self._sslobj.pending()
  241.         return None
  242.  
  243.     
  244.     def unwrap(self):
  245.         if self._sslobj:
  246.             s = self._sslobj.shutdown()
  247.             self._sslobj = None
  248.             return s
  249.         raise None('No SSL wrapper around ' + str(self))
  250.  
  251.     
  252.     def shutdown(self, how):
  253.         self._sslobj = None
  254.         socket.shutdown(self, how)
  255.  
  256.     
  257.     def close(self):
  258.         pass
  259.  
  260.     
  261.     def do_handshake(self):
  262.         '''Perform a TLS/SSL handshake.'''
  263.         self._sslobj.do_handshake()
  264.  
  265.     
  266.     def _real_connect(self, addr, return_errno):
  267.         if self._connected:
  268.             raise ValueError('attempt to connect already-connected SSLSocket!')
  269.         self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile, self.cert_reqs, self.ssl_version, self.ca_certs, self.ciphers)
  270.         
  271.         try:
  272.             if return_errno:
  273.                 rc = socket.connect_ex(self, addr)
  274.             else:
  275.                 rc = None
  276.                 socket.connect(self, addr)
  277.             if not rc:
  278.                 if self.do_handshake_on_connect:
  279.                     self.do_handshake()
  280.                 self._connected = True
  281.             return rc
  282.         except socket_error:
  283.             self._sslobj = None
  284.             raise 
  285.  
  286.  
  287.     
  288.     def connect(self, addr):
  289.         '''Connects to remote ADDR, and then wraps the connection in
  290.         an SSL channel.'''
  291.         self._real_connect(addr, False)
  292.  
  293.     
  294.     def connect_ex(self, addr):
  295.         '''Connects to remote ADDR, and then wraps the connection in
  296.         an SSL channel.'''
  297.         return self._real_connect(addr, True)
  298.  
  299.     
  300.     def accept(self):
  301.         '''Accepts a new connection from a remote client, and returns
  302.         a tuple containing that new connection wrapped with a server-side
  303.         SSL channel, and the address of the remote client.'''
  304.         (newsock, addr) = socket.accept(self)
  305.         
  306.         try:
  307.             return (SSLSocket(newsock, keyfile = self.keyfile, certfile = self.certfile, server_side = True, cert_reqs = self.cert_reqs, ssl_version = self.ssl_version, ca_certs = self.ca_certs, ciphers = self.ciphers, do_handshake_on_connect = self.do_handshake_on_connect, suppress_ragged_eofs = self.suppress_ragged_eofs), addr)
  308.         except socket_error:
  309.             e = None
  310.             newsock.close()
  311.             raise e
  312.  
  313.  
  314.     
  315.     def makefile(self, mode = 'r', bufsize = -1):
  316.         '''Make and return a file-like object that
  317.         works with the SSL connection.  Just use the code
  318.         from the socket module.'''
  319.         self._makefile_refs += 1
  320.         return _fileobject(self, mode, bufsize, close = True)
  321.  
  322.  
  323.  
  324. def wrap_socket(sock, keyfile = None, certfile = None, server_side = False, cert_reqs = CERT_NONE, ssl_version = PROTOCOL_SSLv23, ca_certs = None, do_handshake_on_connect = True, suppress_ragged_eofs = True, ciphers = None):
  325.     return SSLSocket(sock, keyfile = keyfile, certfile = certfile, server_side = server_side, cert_reqs = cert_reqs, ssl_version = ssl_version, ca_certs = ca_certs, do_handshake_on_connect = do_handshake_on_connect, suppress_ragged_eofs = suppress_ragged_eofs, ciphers = ciphers)
  326.  
  327.  
  328. def cert_time_to_seconds(cert_time):
  329.     '''Takes a date-time string in standard ASN1_print form
  330.     ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
  331.     a Python time value in seconds past the epoch.'''
  332.     import time as time
  333.     return time.mktime(time.strptime(cert_time, '%b %d %H:%M:%S %Y GMT'))
  334.  
  335. PEM_HEADER = '-----BEGIN CERTIFICATE-----'
  336. PEM_FOOTER = '-----END CERTIFICATE-----'
  337.  
  338. def DER_cert_to_PEM_cert(der_cert_bytes):
  339.     '''Takes a certificate in binary DER format and returns the
  340.     PEM version of it as a string.'''
  341.     if hasattr(base64, 'standard_b64encode'):
  342.         f = base64.standard_b64encode(der_cert_bytes)
  343.         return PEM_HEADER + '\n' + textwrap.fill(f, 64) + '\n' + PEM_FOOTER + '\n'
  344.     return None + '\n' + base64.encodestring(der_cert_bytes) + PEM_FOOTER + '\n'
  345.  
  346.  
  347. def PEM_cert_to_DER_cert(pem_cert_string):
  348.     '''Takes a certificate in ASCII PEM format and returns the
  349.     DER-encoded version of it as a byte sequence'''
  350.     if not pem_cert_string.startswith(PEM_HEADER):
  351.         raise ValueError('Invalid PEM encoding; must start with %s' % PEM_HEADER)
  352.     if not pem_cert_string.strip().endswith(PEM_FOOTER):
  353.         raise ValueError('Invalid PEM encoding; must end with %s' % PEM_FOOTER)
  354.     d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
  355.     return base64.decodestring(d)
  356.  
  357.  
  358. def get_server_certificate(addr, ssl_version = PROTOCOL_SSLv3, ca_certs = None):
  359.     """Retrieve the certificate from the server at the specified address,
  360.     and return it as a PEM-encoded string.
  361.     If 'ca_certs' is specified, validate the server cert against it.
  362.     If 'ssl_version' is specified, use it in the connection attempt."""
  363.     (host, port) = addr
  364.     if ca_certs is not None:
  365.         cert_reqs = CERT_REQUIRED
  366.     else:
  367.         cert_reqs = CERT_NONE
  368.     s = wrap_socket(socket(), ssl_version = ssl_version, cert_reqs = cert_reqs, ca_certs = ca_certs)
  369.     s.connect(addr)
  370.     dercert = s.getpeercert(True)
  371.     s.close()
  372.     return DER_cert_to_PEM_cert(dercert)
  373.  
  374.  
  375. def get_protocol_name(protocol_code):
  376.     return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')
  377.  
  378.  
  379. def sslwrap_simple(sock, keyfile = None, certfile = None):
  380.     '''A replacement for the old socket.ssl function.  Designed
  381.     for compability with Python 2.5 and earlier.  Will disappear in
  382.     Python 3.0.'''
  383.     if hasattr(sock, '_sock'):
  384.         sock = sock._sock
  385.     ssl_sock = _ssl.sslwrap(sock, 0, keyfile, certfile, CERT_NONE, PROTOCOL_SSLv23, None)
  386.     
  387.     try:
  388.         sock.getpeername()
  389.     except socket_error:
  390.         pass
  391.  
  392.     ssl_sock.do_handshake()
  393.     return ssl_sock
  394.  
  395.